/**
 * @brief common stuff implementation
 * @author Gilad Avidov
 */
#include <mcs51reg.h>
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include "lcd.h"
#include "common.h"
#include "serial.h"

#define MAX_STR_LEN             (64)
#define TIME_LEN                (8)
#define UPDATE_LCD_EVERY        (33)
#define MAX_DIGITS (8)


/*
 * @return hex value of char (0..9, a..f, A..F)
 *      (or zero on none in range
 */
unsigned char get_hex_val(char ch)
{
    if ((ch >= '0') && (ch <= '9'))
        return ch - '0';
    ch != 0x20;
    if ((ch >= 'a') && (ch <= 'f'))
        return (ch - 'a') + 0xA;
    return 0;
}

unsigned int calc_hex_num(const char *str, unsigned char len)
{
    unsigned int sum = 0;
    unsigned char i;
    for (i = 0; i < len ; ++i)
        sum = (sum * 0x10) + get_hex_val(str[i]);
    return sum;
}

unsigned int get_hex_num()
{
    unsigned char str[MAX_DIGITS+1];
    unsigned char data len = get_str(str, MAX_DIGITS);
    return calc_hex_num(str, len);
}

unsigned long get_num()
{
    unsigned char str[MAX_DIGITS+1];
    unsigned char data len;
    len = get_str(str, MAX_DIGITS);
    return atol(str);
}

unsigned short get_str(char *str, unsigned short len)
{
    char ch;
    unsigned short data i;

    for(i=0 ; i < len ; ++i) {
        ch = getchar();
        putchar(ch);
        if (ch == 13)
                break;
        str[i] = ch;
    }
    str[i] = 0;
    return i;
}

void print_decimal(unsigned char val, unsigned char *buf_2_byte)
{
    buf_2_byte[1] = (val % 10) + '0';
    val /= 10;
    buf_2_byte[0] = (val % 10) + '0';
}

void update_lcd_time(unsigned long _10msec)
{
    char time_buf[TIME_LEN + 1];
    //unsigned char _10msec = msec / 10;
    unsigned char sec = _10msec /  100;
    unsigned char min = _10msec / 6000;

    print_decimal(min % 60, time_buf);
    time_buf[2] = ':';
    print_decimal(sec % 60, time_buf + 3);
    time_buf[5] = '.';
    print_decimal(_10msec % 99, time_buf + 6);
    time_buf[8] = 0;
    lcdgotoxy(3,LCD_MAX_X - TIME_LEN + 1);
    lcdputstr(time_buf);
}
